//
//  HomeCell6.m
//  Tunnel
//
//  Created by wbb on 2025/6/5.
//

#import "HomeCell6.h"
#import "HyCategories.h"
#import "HyChartsLineDemoCursor.h"
#import "HyCharts.h"
#import "YJXYVC.h"
#import <WebKit/WebKit.h>
@interface HomeCell6()<WKNavigationDelegate>

@property (nonatomic, strong) WKWebView *webView;
@property (nonatomic, strong) NSArray * titles;
@property (nonatomic, copy) NSArray * valuse;

@property (nonatomic, assign) float maxNum;
@property (nonatomic, assign) float minNum;
@end
@implementation HomeCell6

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
    
    self.tipLab.text  = @"正在发生 0 个应急事件";

    
//    [self setDataSource:@[] titles:@[]];
}

- (void)cellWithData:(id)data {
    [super cellWithData:data];
    NSArray *arr = (NSArray *)data[@"monthCountDtos"];
    
    self.tipLab.text = [NSString stringWithFormat:@"正在发生 %@ 个应急事件",data[@"notFinishedCount"]];
    
    NSMutableArray *nArr = [NSMutableArray arrayWithCapacity:0];
    NSMutableArray *yearMonthArr = [NSMutableArray arrayWithCapacity:0];

    __block NSInteger maxAge = INT_MIN;
    __block NSInteger minAge = INT_MAX;
    [arr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSDictionary *dic = (NSDictionary *)obj;
        
        [yearMonthArr addObject:dic[@"yearMonth"]];
        [nArr addObject:dic[@"n"]];

//        NSString *ydl = [NSString stringWithFormat:@"%.2f", [dic[@"ydl"] floatValue]];
        float value = [dic[@"n"] floatValue];
        if (value > maxAge) {
            maxAge = value;
        }
        if (value < minAge) {
            minAge = value;
        }
    }];
    
    self.minNum = minAge;
    self.maxNum = maxAge;
    
    [self setDataSource:nArr titles:yearMonthArr];
//    NSArray *alarmDeviceList = [NSArray arrayWithArray:dic[@"alarmDeviceList"]];
//    [self dataWithArr:alarmDeviceList andNum:[dic[@"alarmNum"]?:@"0" integerValue]];
}
- (void)setDataSource:(NSArray *)valuse titles:(NSArray *)titles {
    _titles = titles;
    _valuse = valuse;
//    UIView *oneChartView =  [self oneChartLinViewWithFrame:CGRectMake(15, 0, kSCREEN_WIDTH -30 - 24, ScaleNum(150))];
//    [self.bgView addSubview:oneChartView];
    
    [self loadWebView];
}
- (void)loadWebView {
    if(self.webView) {
        [self.webView reload];
        return;
    }
    // 初始化WKWebView配置
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    
    // 创建WKWebView
    self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(15, 10, kSCREEN_WIDTH -30 - 24, ScaleNum(162)) configuration:config];
    self.webView.navigationDelegate = self;
//    self.webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.bgView addSubview:self.webView];
    self.webView.scrollView.scrollEnabled = NO;
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.bottom.offset(0);
    }];
    // 加载本地HTML文件（确保HTML文件已添加到项目中，并勾选了对应的target）
    NSString *htmlPath = [[NSBundle mainBundle] pathForResource:@"LineCharts" ofType:@"html"];
    NSURL *fileURL = [NSURL fileURLWithPath:htmlPath];
    NSURLRequest *request = [NSURLRequest requestWithURL:fileURL];
    [self.webView loadRequest:request];
}

- (UIView *)oneChartLinViewWithFrame:(CGRect)frame {
    
    UIView *contentView = [[UIView alloc] initWithFrame:frame];
    contentView.backgroundColor = UIColor.whiteColor;
    contentView.layer.cornerRadius = 5;
    contentView.layer.borderWidth = 1.0;
    contentView.layer.borderColor = UIColor.groupTableViewBackgroundColor.CGColor;
    contentView.clipsToBounds = NO;
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, CGRectGetWidth(frame) - 20, 0)];
    titleLabel.text = @"";
    titleLabel.font = [UIFont systemFontOfSize:17];
    titleLabel.textColor = UIColor.darkTextColor;
    [contentView addSubview:titleLabel];
    
    HyChartLineView *chartLineView =  [[HyChartLineView alloc] initWithFrame:CGRectMake(10, CGRectGetMaxY(titleLabel.frame) + 15, CGRectGetWidth(titleLabel.frame), CGRectGetHeight(frame) - CGRectGetMaxY(titleLabel.frame) - 25)];
    [contentView addSubview:chartLineView];
    
    chartLineView.contentEdgeInsets = UIEdgeInsetsMake(0, 35, 35, 10);
    chartLineView.pinchGestureDisabled = YES;
    
    // 自定义游标
    HyChartsLineDemoCursor *cursor = HyChartsLineDemoCursor.new;
    cursor.showView = chartLineView;
    [chartLineView resetChartCursor:cursor];
    kWEAK_SELF;
    // 配置坐标轴
    [[chartLineView.dataSource.axisDataSource configXAxisWithModel:^(id<HyChartXAxisModelProtocol>  _Nonnull xAxisModel) {
        xAxisModel.topXaxisDisabled = NO;
        [[[xAxisModel configNumberOfIndexs:5] configBottomXAxisInfo:^(id<HyChartXAxisInfoProtocol>  _Nonnull xAxisInfo) {
//            xAxisInfo.rotateAngle = - M_PI_4;
            xAxisInfo.axisTextFont = [UIFont systemFontOfSize:14];
            xAxisInfo.displayAxisZeroText = NO;
        }] configTopXAxisInfo:^(id<HyChartXAxisInfoProtocol>  _Nonnull xAxisInfo) {
            xAxisInfo.autoSetText = NO;
            xAxisInfo.axisLineWidth = 1;
            xAxisInfo.axisLineColor = UIColor.groupTableViewBackgroundColor;
        }];
    }] configYAxisWithModel:^(id<HyChartYAxisModelProtocol>  _Nonnull yAxisModel) {
        [[[[yAxisModel configNumberOfIndexs:5] configYAxisMaxValue:^NSNumber * _Nonnull{
            return weakSelf.maxNum < 5 ? @5 : @(weakSelf.maxNum);
        }] configLeftYAxisInfo:^(id<HyChartYAxisInfoProtocol>  _Nonnull yAxisInfo) {
            yAxisInfo.axisTextFont = [UIFont systemFontOfSize:14];
            yAxisInfo.axisTextPosition = HyChartAxisTextPositionBinus;
            yAxisInfo.axisLineType = HyChartAxisLineTypeNone;
            yAxisInfo.displayAxisZeroText = NO;
        }] configYAxisMinValue:^NSNumber * _Nonnull{
            return  @(weakSelf.minNum);
        }];
    }];
    
    // 配置图表信息
    [chartLineView.dataSource.configreDataSource configConfigure:^(id<HyChartLineConfigureProtocol>  _Nonnull configure) {
        configure.width = 0;
        configure.autoMargin = YES;
        [configure configLineConfigureAtIndex:^(NSInteger index, id<HyChartLineOneConfigureProtocol>  _Nonnull oneConfigure) {
            
            oneConfigure.lineWidth = 2;
            oneConfigure.lineColor = hexColor(FF3245);
            oneConfigure.lineType = HyChartLineTypeCurve;
            
            oneConfigure.linePointWidth = .5;
            oneConfigure.linePointSize = CGSizeMake(5, 5);
            oneConfigure.linePointType = HyChartLinePointTypeRing;
            oneConfigure.linePointFillColor = UIColor.whiteColor;
            oneConfigure.shadeColors = @[[UIColor colorWithRed:255/255.0 green:50/255.0 blue:69/255.0 alpha:.8], [UIColor colorWithRed:255/255.0 green:50/255.0 blue:69/255.0 alpha:.6], [UIColor colorWithRed:255/255.0 green:50/255.0 blue:69/255.0 alpha:.4] ,[UIColor colorWithRed:255/255.0 green:50/255.0 blue:69/255.0 alpha:.2], [UIColor colorWithRed:255/255.0 green:50/255.0 blue:69/255.0 alpha:.1]];
        }];
    }];
    
    NSArray<NSString *> *titles =weakSelf.titles;// @[@"03-08", @"03-09", @"03-10", @"03-11", @"03-12", @"03-13", @"03-14", @"03-18", @"03-19"];
    NSMutableArray<NSNumber *> *values = weakSelf.valuse.mutableCopy;
//    [titles enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//        [values addObject:@((int)(arc4random() % 10000))];
//    }];
    
    // 配置数据
    [[chartLineView.dataSource.modelDataSource configNumberOfItems:^NSInteger{
        return values.count;
    }] configModelForItemAtIndex:^(id<HyChartLineModelProtocol>  _Nonnull model, NSInteger index) {
        model.text = titles[index];
        model.values = @[values[index]];
        // 自定义数据
        NSDictionary *dict = @{@"colors" : @[hexColor(FF3245)],@"texts" : @[@"数量"]};
        model.exData = dict;
    }];
    

    [chartLineView setNeedsRendering];
    
    return contentView;
}

- (IBAction)loadMore:(id)sender {
    YJXYVC *vc = [[YJXYVC alloc] init];
    [[WDGlobal getCurrentViewController].navigationController pushViewController:vc animated:NO];
}


#pragma mark - WKNavigationDelegate

// 网页加载完成后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    // 准备要传递给网页的数据
    //    NSArray *xData = @[@"衬衫", @"羊毛衫", @"雪纺衫", @"裤子", @"高跟鞋", @"袜子", @"连衣裙", @"外套"];
    //    NSArray *yData = @[@5, @20, @36, @10, @15, @25, @30, @18];
//    NSLog(@"%@,%@",self.titles,self.values);
    // 将OC数组转换为JSON字符串
    NSString *xJsonStr = [WDGlobal convertArrayToJsonString:self.titles];
    NSString *yJsonStr = [WDGlobal convertArrayToJsonString:self.valuse];
    
    if (xJsonStr && yJsonStr) {
        // 构建JavaScript代码
        NSString *jsCode = [NSString stringWithFormat:@"updateChart(%@, %@);", xJsonStr, yJsonStr];
        
        // 执行JavaScript代码
        [webView evaluateJavaScript:jsCode completionHandler:^(id _Nullable result, NSError * _Nullable error) {
            if (error) {
                NSLog(@"调用JavaScript失败: %@", error.localizedDescription);
            } else {
                NSLog(@"数据已成功传递到网页");
            }
        }];
    } else {
        NSLog(@"JSON转换失败");
    }
}
@end
